# This file is part of Laivsys 2. See doc/README_FOR_APP for more information
# and licence.
# (C) Sigve Indregard
# $Id: laiv.rb 57 2008-01-30 23:40:41Z sigve.indregard $

# This class represents a single laiv project. The laiv project is the most
# fundamental object. All other objects except user-related objects reside
# within a laiv.
class Laiv < ActiveRecord::Base
  belongs_to :administrator, :class_name => 'User', :foreign_key => 'administrator_id'

  has_many :laiv_users
  has_many :users, :through => :laiv_users

  has_many :application_forms
  has_many :applicants, :through => :application_forms, :source => :user

  has_many :participations, :class_name => 'ApplicationForm', 
    :conditions => "status=#{ApplicationForm::STATUS_ACCEPTED}"
  has_many :pending_forms, :class_name => 'ApplicationForm',
    :conditions => "status=#{ApplicationForm::STATUS_PENDING}"
  has_many :refused_forms, :class_name => 'ApplicationForm',
    :conditions => "status=#{ApplicationForm::STATUS_REFUSED}"

  has_many :participants, :through => :participations, :source => :user

  has_many :roles, :dependent => :destroy

  validates_presence_of :administrator_id
  validates_associated :administrator
  validates_presence_of :title

  def validate
    unless (starts_on==nil and ends_on==nil) or ends_on >= starts_on
      errors.add_to_base "The laiv must end after it starts."
    end
  end

  # Returns a string representing the laivs timespan. If end date equals start
  # date, it is returned only once.
  def timespan
    if starts_on == ends_on
      starts_on.to_s
    else
      "#{starts_on.to_s}-#{ends_on.to_s}"
    end
  end

  def title_with_year
    if starts_on and starts_on.to_time < Time.now and Time.now.year != starts_on.year
      "#{title} (#{starts_on.year})"
    else
      title
    end
  end
end
